package com.pkk.penguin.frame.know.java.interview.year2021.atguigu_20210226.aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import org.junit.Test;

/**
 * aqs的抽象队列同步器
 *
 * @author peikunkun
 * @version V1.0
 * @date 2021-03-09 15:28
 **/
public class AQSDemo {


  @Test
  public void Administrator_14_20210309153107_() {
    System.out.println("欢迎使用单元测试方法【Administrator_14()_20210309153107】");
    System.out.println("此方法测试描述：【】");

    //默认非公平锁
    final ReentrantLock reentrantLock = new ReentrantLock(false);

    //可以用于银行办理业务,银行办理业务窗口一个,现在来了三个人进行排队办理


    /*设计的主要知识点:
     *①：AQS抽象队列同步器是由status(int类型volatile的状态)+Node(双向的链表)组成
     * ②:主要是通过LockSupport.park()进行抢不到线程阻塞，通过unlock进行释放唤醒队列的下一个线程
     * ③：
     *
     *
     * */

    new Thread(new Runnable() {
      @Override
      public void run() {
        reentrantLock.lock();
        try {

          try {
            //A办理业务需要20分钟
            TimeUnit.MINUTES.sleep(20L);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }

        } finally {
          reentrantLock.unlock();
        }
      }
    }, "Thread-顾客A").start();

    new Thread(new Runnable() {
      @Override
      public void run() {
        reentrantLock.lock();
        try {

          try {
            //B办理业务需要20分钟
            TimeUnit.MINUTES.sleep(30L);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }

        } finally {
          reentrantLock.unlock();
        }
      }
    }, "Thread-顾客B").start();

    new Thread(new Runnable() {
      @Override
      public void run() {
        reentrantLock.lock();
        try {

          try {
            //C办理业务需要20分钟
            TimeUnit.MINUTES.sleep(10L);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }

        } finally {
          reentrantLock.unlock();
        }
      }
    }, "Thread-顾客C").start();


  }
}
